#include <system.h>
#include "kegscale_mk2.h"
#include "eeprom_utils.h"
#include "ports.h"
#include "utils.h"

#ifndef USE_PICPACK
#include <lcd_driver.h>

#else

#include "lcd.h"
#define lcd_gotoxy(x,y) (1)
#define lcd_datamode() (1)
#define lcd_write(x) lcd_write_data(x)
#define lprintf(x) lcd_write_data_str(x)
#define lcd_clear() lcd_clear_display()
#define lcd_setup() lcd_setup(); lcd_init();
#endif

void initialize_lcd() {
    lcd_setup();
    lcd_clear();
}

void set_pints_left(uint8_t row, uint8_t msd, uint8_t lsd) {
    uint8_t lcd_width  = eeprom_read(LCD_WIDTH_ADDR);
    lcd_gotoxy(lcd_width - 3, row);
    lcd_datamode();
    lcd_write(' ');
    lcd_write(msd);
    lcd_write(lsd);
}

void update_display(uint8_t page) {
    uint8_t i;

    uint8_t lcd_height = eeprom_read(LCD_HEIGHT_ADDR);
    uint8_t lcd_width = eeprom_read(LCD_WIDTH_ADDR);
    uint8_t num_kegs   = eeprom_read(NUM_KEGS_ADDR);
    uint8_t start_keg = page * lcd_height;
    uint8_t row = 0;
    eepaddr_t ptr = KEG_NAME_ADDR + (lcd_width - 2) * start_keg;
    for (i = start_keg; i < num_kegs && i < start_keg + lcd_height; i++, row++) {
        uint8_t msd, lsd;
        lcd_gotoxy(0, row);
        lcd_datamode();
        while(1) {
            uint8_t c1 = eeprom_read(ptr++);
            if(c1 == 0)
                break;
            lcd_write(c1);
        }
        uint8_t pints =  num_pints[i] / 128;
        msd = pints / 10;
        lsd = pints % 10;
        set_pints_left(row, msd + '0', lsd + '0');
    }
}

void show_version() {
    char width = eeprom_read(LCD_WIDTH_ADDR);
    width -= 12;
    if(width < 0)
        width = 0;
    width >>= 1;
    lcd_gotoxy(width, 0);
    lprintf((rom char *)"KegScale Mk2");
    lcd_gotoxy(width, 1);
    lprintf((rom char *)"Version ");
    lprintf(version);
}
uint8_t get_num_pages() {
    uint8_t lcd_height = eeprom_read(LCD_HEIGHT_ADDR);
    uint8_t num_kegs   = eeprom_read(NUM_KEGS_ADDR);
    uint8_t count = 1;
    uint8_t ptr = lcd_height;
    while(ptr < num_kegs) {
        count++;
        ptr += lcd_height;
    }
    return count;
}
